<template>
  <el-form
    :model="ruleForm"
    :rules="rules"
    ref="ruleForm"
    status-icon
    label-width="100px"
    class="demo-ruleForm"
  >
    <el-form-item label="账号" prop="username">
      <el-input type="text" v-model="ruleForm.username" auto-complete="off"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input type="password" v-model="ruleForm.password" auto-complete="off"></el-input>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
      <el-button @click="resetForm('ruleForm')">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import Cookies from "js-cookie";
export default {
  props: ["url"],
  data() {
    return {
      ruleForm: {
        username: "",
        password: ""
      },
      rules: {
        username: [
          { required: true, message: "请输入账号", trigger: "blur" },
          { min: 5, max: 20, message: "长度在 5 到 20 个字符", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }]
      }
    };
  },
  methods: {
    async submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (!valid) {
          this.$notify.error({
            title: "错误",
            message: "表单格式错误"
          });
          return false;
        } else {
          this.loginPost();
          return true;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    async loginPost() {
      try {
        let that = this;
        let { status, data } = await this.$axios.post(this.url, this.ruleForm);

        let user = JSON.parse(JSON.stringify(data));
        this.$store.commit("user/current", user);
        data.name =  encodeURIComponent(data.name);
        document.cookie = "current=" + JSON.stringify(data);
     
        this.$notify.success({
          title: "成功",
          message: "登录成功",
          duration: 2000,
          onClose: () => {
             that.$router.go(-1);
          }
        });
      } catch ({
        response: {
          status,
          data: { error_msg }
        }
      }) {
        this.$notify.error({
          title: "错误",
          message: "账号密码不匹配"
        });
      }
    }
  }
};
</script>

<style scoped>
</style>